/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.weiyi.chat;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.Log;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.weiyi.chat.common.Constant;
import com.weiyi.chat.common.DemoHelper;
import com.weiyi.chat.domain.User;
import com.weiyi.chat.utils.PreferenceUtil;


import java.util.Iterator;
import java.util.List;

// ============== fabric start
//import com.crashlytics.android.Crashlytics;
//import io.fabric.sdk.android.Fabric;
// ============== fabric end

public class MyApplication extends Application {

	public static Context applicationContext;
	private static MyApplication instance;
	private static User.BodyBean mUser;
	private static String mToken;
	// login user name
	public final String PREF_USERNAME = "username";
	
	/**
	 * nickname for current user, the nickname instead of ID be shown when user receive notification from APNs
	 */
	public static String currentUserNick = "";
	private String TAG = "test";

	public static synchronized Context getContext() {
		return instance;
	}

	@Override
	public void onCreate() {
		MultiDex.install(this);
		super.onCreate();
// ============== fabric start
//		Fabric.with(this, new Crashlytics());
// ============== fabric end
        applicationContext = this;
        instance = this;

		int pid = android.os.Process.myPid();
		String processAppName = getAppName(pid);
		// 如果APP启用了远程的service，此application:onCreate会被调用2次
		// 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
		// 默认的APP会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回

		if (processAppName == null ||!processAppName.equalsIgnoreCase(applicationContext.getPackageName())) {
			Log.e(TAG, "enter the service process!");

			// 则此application::onCreate 是被service 调用的，直接返回
			return;
		}

		//init demo helper
		DemoHelper.getInstance().init(applicationContext);

		EMOptions options = new EMOptions();
		// 默认添加好友时，是不需要验证的，改成需要验证
		options.setAcceptInvitationAlways(false);
		options.setAutoLogin(false);
		//初始化
		EMClient.getInstance().init(applicationContext, options);
		//在做打包混淆时，关闭debug模式，避免消耗不必要的资源
		EMClient.getInstance().setDebugMode(true);
		//以下都不是必须的，根据需要自行选择


//		//添加通讯录监听
//		initContactListener();
//		//添加消息的监听
//		initMessageListener();
//		//监听连接状态的改变
//		initConnectionListener();

//		//red packet code : 初始化红包SDK，开启日志输出开关
//		RedPacket.getInstance().initRedPacket(applicationContext, RPConstant.AUTH_METHOD_EASEMOB, new RPInitRedPacketCallback() {
//
//			@Override
//			public void initTokenData(RPValueCallback<TokenData> callback) {
//				TokenData tokenData = new TokenData();
//				tokenData.imUserId = EMClient.getInstance().getCurrentUser();
//				//此处使用环信id代替了appUserId 开发者可传入App的appUserId
//				tokenData.appUserId = EMClient.getInstance().getCurrentUser();
//				tokenData.imToken = EMClient.getInstance().getAccessToken();
//				//同步或异步获取TokenData 获取成功后回调onSuccess()方法
//				callback.onSuccess(tokenData);
//			}
//
//			@Override
//			public RedPacketInfo initCurrentUserSync() {
//				//这里需要同步设置当前用户id、昵称和头像url
//				String fromAvatarUrl = "";
//				String fromNickname = EMClient.getInstance().getCurrentUser();
//				EaseUser easeUser = EaseUserUtils.getUserInfo(fromNickname);
//				if (easeUser != null) {
//					fromAvatarUrl = TextUtils.isEmpty(easeUser.getAvatar()) ? "none" : easeUser.getAvatar();
//					fromNickname = TextUtils.isEmpty(easeUser.getNick()) ? easeUser.getUsername() : easeUser.getNick();
//				}
//				RedPacketInfo redPacketInfo = new RedPacketInfo();
//				redPacketInfo.fromUserId = EMClient.getInstance().getCurrentUser();
//				redPacketInfo.fromAvatarUrl = fromAvatarUrl;
//				redPacketInfo.fromNickName = fromNickname;
//				return redPacketInfo;
//			}
//		});
//		RedPacket.getInstance().setDebugMode(true);
		//end of red packet code
	}

	public static MyApplication getInstance() {
		return instance;
	}


	public static void setToken(String token) {
		mToken = token;
		PreferenceUtil.setEdit(Constant.SP_TOKEN, token, instance);
	}

	public static String getToken() {
		if (TextUtils.isEmpty(mToken)) {
			mToken = (String) PreferenceUtil.getValue(Constant.SP_TOKEN, instance);
		}
		return mToken;
	}

	public static void exitLogin() {
//		SPUtils.put(instance, Constant.SP_ISLOGIN, false);
//		SPUtils.put(instance, Constant.SP_TOKEN, "");
//		SPUtils.remove(instance, Constant.SP_USER);
//		SPUtils.clear(instance);
		PreferenceUtil.clearAll(instance);
		mUser = null;
		mToken = "";
	}

//	private void initContactListener() {
//		EMClient.getInstance().contactManager().setContactListener(new EMContactListener() {
//			@Override
//			public void onContactAdded(String s) {
//				//好友请求被同意
//				//发出通知让ContactFragment更新UI
//				EventBus.getDefault().post(new OnContactUpdateEvent(s, true));
//			}
//
//			@Override
//			public void onContactDeleted(String s) {
//				//被删除时回调此方法
//				EventBus.getDefault().post(new OnContactUpdateEvent(s, false));
//				Log.d(TAG, "onContactDeleted: " + s);
//			}
//
//			@Override
//			public void onContactInvited(String username, String reason) {
//				//收到好友邀请
//				Log.d(TAG, "onContactInvited: " + username + "/" + reason);
//				//同意或者拒绝
//				try {
//					EMClient.getInstance().contactManager().acceptInvitation(username);
//				} catch (HyphenateException e) {
//					e.printStackTrace();
//				}
//			}
//
//			@Override
//			public void onFriendRequestAccepted(String s) {
//
//			}
//
//			@Override
//			public void onFriendRequestDeclined(String s) {
//
//			}
//
//			@Override
//			public void onContactAgreed(String s) {
//				//增加了联系人时回调此方法
//			}
//
//			@Override
//			public void onContactRefused(String s) {
//				//好友请求被拒绝
//			}
//		});
//	}
//
//	private void initMessageListener() {
//		EMClient.getInstance().chatManager().addMessageListener(new MessageListenerAdapter() {
//			@Override
//			public void onMessageReceived(List<EMMessage> list) {
//				super.onMessageReceived(list);
//				if (list != null && list.size() > 0) {
//					/**
//					 * 1. 判断当前应用是否在后台运行
//					 * 2. 如果是在后台运行，则发出通知栏
//					 * 3. 如果是在后台发出长声音
//					 * 4. 如果在前台发出短声音
//					 */
//					if (isRuninBackground()) {
//						sendNotification(list.get(0));
//						//发出长声音
//						//参数2/3：左右喇叭声音的大小
//						mSoundPool.play(mYuluSound,1,1,0,0,1);
//					} else {
//						//发出短声音
//						mSoundPool.play(mDuanSound,1,1,0,0,1);
//					}
//					EventBus.getDefault().post(list.get(0));
//				}
//			}
//		});
//	}
//
//
//	private void initConnectionListener() {
//		EMClient.getInstance().addConnectionListener(new EMConnectionListener() {
//			@Override
//			public void onConnected() {
//			}
//
//			@Override
//			public void onDisconnected(int i) {
//				if (i== EMError.USER_LOGIN_ANOTHER_DEVICE){
//					// 显示帐号在其他设备登录
//					/**
//					 *  将当前任务栈中所有的Activity给清空掉
//					 *  重新打开登录界面
//					 */
//					for (BaseActivity baseActivity : mBaseActivityList) {
//						baseActivity.finish();
//					}
//
//					Intent intent = new Intent(QQApplication.this, LoginActivity.class);
//					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//					startActivity(intent);
//					ThreadUtils.runOnMainThread(new Runnable() {
//						@Override
//						public void run() {
//							ToastUtils.showToast(QQApplication.this,"您已在其他设备上登录了，请重新登录。");
//						}
//					});
//
//				}
//			}
//		});
//	}

	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
		MultiDex.install(this);
	}

	private String getAppName(int pID) {
		String processName = null;
		ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
		List l = am.getRunningAppProcesses();
		Iterator i = l.iterator();
		PackageManager pm = this.getPackageManager();
		while (i.hasNext()) {
			ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
			try {
				if (info.pid == pID) {
					processName = info.processName;
					return processName;
				}
			} catch (Exception e) {
			}
		}
		return processName;
	}
}
